% Matlab code to visualize the equilibrium and illustrate the spirals

% To run this file seperately, specify the root directly below:
% cd 'C:/Users/Jilun/Dropbox/WorldEconomy_RiskIntolerance/paper RFS final submission/replication/numerical and calibration exercises'


% Figure A1
% Make the figures for optimal LSAPs with respect to z0 and l
% Caveat: Both comparative statics require banks not to be bankrupt at the optimal LSAP
% 

clear all;
global g rho sigma PStar taub tauh k l tau tauBarBench zBarBench zTildeBench
global z0_2
loadVariables; % Sets the above parameters and the baseline shocks
lBench = l;

global etag 
etag = 0.1;
global taum taug
taum = tauBarBench;
taug = taum; % Make the government as risk averse as the market

%%%%%%%%%%%%%%%%%%%%%
% First calculate the comparative statics

%%%%%%%%%%%%%%%%%%%%%
% Comparative statics for z0
zMin = zTildeBench + 0.1*(zBarBench-zTildeBench);
zMax = zTildeBench + 0.9*(zBarBench-zTildeBench);
z0Arr = [zMin:0.01:zMax];
lsapMaxArr = z0Arr*0;
% Make sure lower bound is such that the equilibrium is unique
for i=1:length(z0Arr)
    z0 = z0Arr(i);
eq = solveOptimalLSAP(etag,taug,taum,z0);
lsapMaxSupplyArr(i) =eq.lsapMax;
eqMaxSupplyArr(i) = eq;
end

%%%%%%%%%%%%%%%%%%%%%
% Comparative statics for l
% As we change l, we "recalibrate taub to leave the effective risk
% (So the main change is that banks support the same tolerance with lower
% wealth and greater willingness to take risk)

% Start with z0 closer to the upper threshold for the benchmark case
z0 = zTildeBench + (zBarBench-zTildeBench)*0.5; % Choose between zTilde and zBar, closer to zBar
lArr = [lBench:0.01:lBench*1.05];
for i=1:length(lArr)
   l = lArr(i);
   taub = fsolve(@(tb) tb*k*(1-l)+tauh*(1-k*(1-l)) - tauBarBench,taub);
   % Leave the remaining parameters unchanged
   % taum = tauBarBench; This didn't change since tauBarBench is the same
   eq = solveOptimalLSAP(etag,taug,taum,z0);
   lsapMaxLeverageArr(i) =eq.lsapMax;
   eqMaxLeverageArr(i) = eq;
end

%%%%%%%%%%%%%%%%%%%%%
% Now plot the curves in side-by-side panels
figure('Position',[30 30 1130 530]);
subplot(1,2,1);
hold on;
 plot(z0Arr,lsapMaxSupplyArr,'b','LineWidth',3);
xlabel('Severity of the supply shock: $z_0$ on inverted scale','Interpreter','Latex','FontSize',20);
titleStr = sprintf('Optimal LSAP, $\\lambda$');
title(titleStr,'Interpreter','Latex','FontSize',20);
set(gca, 'XDir','reverse');
xlim([min(z0Arr) max(z0Arr)]);
ylim([lsapMaxSupplyArr(end) lsapMaxSupplyArr(1)]);

subplot(1,2,2);
hold on;
plot(lArr,lsapMaxLeverageArr,'b','LineWidth',3);
xlabel('Leverage $l_0$ (fixing effective risk tolerance, $\tau_0(1)$)','Interpreter','Latex','FontSize',20);
titleStr = sprintf('Optimal LSAP, $\\lambda$');
title(titleStr,'Interpreter','Latex','FontSize',20);
xlim([min(lArr) max(lArr)]);
ylim([lsapMaxLeverageArr(1) lsapMaxLeverageArr(end)]);

saveas(gcf,[pwd '/figures/figA1.eps'],'epsc');

